package com.wave.wavesystem.common.util;

import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import com.wave.wavesystem.common.pojo.entity.IpInfoEntity;
import wave.common.pojo.enums.RStatusEnum;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 夕下风波
 * @date 2025-02-02 22:55
 * @description 网络工具类
 */
public class WebUtil {

    /**
     * 获取当前请求
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ThrowUtil.throwIf(Func.isEmpty(requestAttributes), RStatusEnum.SYS_ERROR);
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 获取当前请求ip地址
     */
    public static String getIp() {
        HttpServletRequest request = getRequest();
        String clientIp = request.getHeader("X-Forwarded-For");
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Real-IP");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }

    /**
     * 获取ip信息
     */
    public static IpInfoEntity getIpInfo() {
        String ip = getIp();
        // 获取IP信息
        IPInfo ipInfo = IPInfoUtils.getIpInfo(ip);
        IpInfoEntity ipInfoEntity = new IpInfoEntity();
        ipInfoEntity.setCountry(ipInfo.getCountry());
        ipInfoEntity.setProvince(ipInfo.getProvince());
        ipInfoEntity.setAddress(ipInfo.getAddress());
        ipInfoEntity.setIsp(ipInfo.getIsp());
        ipInfoEntity.setIp(ip);
        return ipInfoEntity;
    }

}
